package com.example.demo.mongo.demo;

import com.example.demo.mongo.converter.MoneyReadConverter;
import com.example.demo.mongo.model.MongoCoffee;
import com.mongodb.client.result.UpdateResult;
import lombok.extern.slf4j.Slf4j;
import org.joda.money.CurrencyUnit;
import org.joda.money.Money;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.convert.MongoCustomConversions;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.data.mongodb.core.query.Update;

import java.util.Arrays;
import java.util.Date;
import java.util.List;

/**
 * @author: YsCy丶
 * @Date: 2020/8/1 18:50
 * @descrption MongoDB调用示例
 */
@Slf4j
public class Mongo  {

    @Autowired
    private MongoTemplate mongoTemplate;

    @Bean
    public MongoCustomConversions mongoCustomConversions(){
        return new MongoCustomConversions(Arrays.asList(new MoneyReadConverter()));
    }

    private void playWithMongodb() throws InterruptedException {
        //提交测试
        MongoCoffee latte = MongoCoffee.builder()
                .name("latte")
                .price(Money.of(CurrencyUnit.of("CNY"),20.0))
                .createTime(new Date())
                .updateTime(new Date())
                .build();
        MongoCoffee coffee = mongoTemplate.save(latte);
        log.info("MongoCoffee:{}",coffee);
        List<MongoCoffee> list = mongoTemplate.find(
                Query.query(Criteria.where("name").is("latte")),MongoCoffee.class);
        log.info("Find {} MongoCoffee",list.size());
        list.forEach(mongoCoffee -> log.info("MongoCoffee {}",mongoCoffee));

        Thread.sleep(1000);//为了看更新时间
        UpdateResult result = mongoTemplate.updateFirst(Query.query(Criteria.where("name").is("latte")),
                new Update().set("price",Money.ofMajor(CurrencyUnit.of("CNY"),30))
                        .currentDate("updateTime"),
                MongoCoffee.class);
        log.info("Update Result:{}",result.getModifiedCount());
        MongoCoffee updateOne = mongoTemplate.findById(coffee.getId(),MongoCoffee.class);
        log.info("Update Result:{}",updateOne);
        mongoTemplate.remove(updateOne);

    }
}
